﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.EntityFramework.Core
{
    public class RemoveForeignKeysHelper
    {
        //定义个全局变量，用来存储需要移除的级联属性
        internal static ConcurrentDictionary<string, List<string>> RemoveForeignKeys = new ConcurrentDictionary<string, List<string>>();

        public static void ExecuForeignKeys(CreateTableOperation operation, IModel model)
        {
            var entityName = model.GetRelationalModel()
                .FindTable(operation.Name, operation.Schema).EntityTypeMappings
                .FirstOrDefault()?.EntityType.Name;

            if (RemoveForeignKeys.TryGetValue(entityName, out List<string> columns))
            {
                operation.ForeignKeys
                    .Where(item => item.Columns.Intersect(columns).Count() > 0)
                    .ToList()
                    .ForEach(item => operation.ForeignKeys.Remove(item));
            }
        }
    }
}
